<!--页面同时显示value和code，输入两者 都可以搜索 和JSearchSelect的唯一区别就是是否显示code和搜索-->
<template>

  <a-select
    v-if="async"
    ref="refName"
    @focus="getNextFocus"
    @mouseenter="clickflag=false"
    @mouseleave="clickflag=true"
    showSearch
    labelInValue
    :disabled="disabled"
    @search="loadData"
    :placeholder="placeholder"
    v-model="selectedAsyncValue"
    style="width: 100%"
    :filterOption="false"
    @change="handleAsyncChange"
    allowClear
    :notFoundContent="loading ? undefined : null"
  >
    <a-spin v-if="loading" slot="notFoundContent" size="small"/>
    <a-select-option disabled v-if="selectNullShow" key="asd" value="">请选择</a-select-option>
    <a-select-option v-for="d in options" :key="d.value" :value="d.value">{{ d.value+'-'+ d.text }}</a-select-option>
  </a-select>

  <a-select
    v-else
    showSearch
    ref="refName"
    @focus="getNextFocus"
    @mouseenter="clickflag=false"
    @mouseleave="clickflag=true"
    :disabled="disabled"
    :placeholder="placeholder"
    optionFilterProp="children"
    style="width: 100%"
    @change="handleChange"
    :filterOption="filterOption"
    v-model="selectedValue"
    allowClear
    :notFoundContent="loading ? undefined : null">
    <a-spin v-if="loading" slot="notFoundContent" size="small"/>
    <a-select-option disabled v-if="selectNullShow" key="asd" value="">请选择</a-select-option>
    <a-select-option v-for="d in options" :key="d.value" :value="d.value">{{ d.value+'-'+ d.text }}</a-select-option>
  </a-select>

</template>

<script>
  import { ajaxGetDictItems } from '@/api/api'
  import debounce from 'lodash/debounce';
  import { getAction } from '../../api/manage'

  export default {
    name: 'JSearchSelectTag',
    props:{
      disabled: Boolean,
      value: String,
      dict: String,
      dictOptions: Array,
      async: Boolean,
      placeholder:{
        type:String,
        default:"请选择",
        required:false
      }
    },
    data(){
      this.loadData = debounce(this.loadData, 100);//消抖
      this.lastLoad = 0;
      return {
        loading:false,
        selectedValue:[],
        selectedAsyncValue:[],
        options: [],
        clickflag:true,
        selectNullShow:true,
      }
    },
    created(){
      this.initDictData();
    },
    watch:{
      "value":{
        immediate:true,
        handler(val){
          if(!val){
            this.selectedValue=[]
            this.selectedAsyncValue=[]
          }else{
            this.initSelectValue()
          }
        }
      },
      "dict":{
        handler(){
          this.initDictData()
        }
      }
    },
    methods:{
      initSelectValue(){
       /* if(this.selectedAsyncValue || this.selectedAsyncValue.key||this.selectedValue){
          this.selectNullShow=false
        }*/
        if(this.async){
          if(!this.selectedAsyncValue || !this.selectedAsyncValue.key || this.selectedAsyncValue.key!=this.value){
            //console.log("这才请求后台")
            getAction(`/sys/dict/loadDictItem/${this.dict}`,{key:this.value}).then(res=>{
              if(res.success){
                let obj = {
                  key:this.value,
                  label:res.result
                }
                this.selectedAsyncValue = {...obj}
              }
            })
          }
        }else{
          this.selectedValue = this.value
        }
      },
      loadData(value){
        //console.log("数据加载",value)
        this.lastLoad +=1
        const currentLoad = this.lastLoad
        this.options = []
        this.loading=true

        if(value){
          this.selectNullShow=false
        }

        if(this.dictOptions){
          if (this.dictOptions && this.dictOptions.length > 0) {
            this.loading = false
            const data=[]
            for(var i=0;i<this.dictOptions.length;i++){
              let r=this.dictOptions[i]

              if (r.value.toUpperCase().startsWith(value.toUpperCase().trim())  ) {
                data.push({
                  value: r.value,
                  text: r.text,
                });
              }
              if(data.length == 10){
                this.options=data
                break
              }

            }
            this.dictOptions.forEach(r => {
              if (r.value.startsWith(value) && value && data.length <= 10) {
                this.options.push({
                  value: r.value,
                  text: r.text,
                });

              }
            });


          }
        }else {
          // 字典code格式：table,text,code
          getAction(`/sys/dict/cacheDict/${this.dict}`, { keyword: value }).then(res => {
            this.loading = false
            if (res.success) {
              if (currentLoad != this.lastLoad) {
                return
              }
              this.options = res.result
              //console.log("我是第一个",res)
            } else {
              this.$message.warning(res.message)
            }
          })

        }


      },
      initDictData(){
        if(!this.async){
          //如果字典项集合有数据
          if(this.dictOptions && this.dictOptions.length>0){
            this.options = [...this.dictOptions]
          }else{
            //根据字典Code, 初始化字典数组
            ajaxGetDictItems(this.dict, null).then((res) => {
              if (res.success) {
                this.options = res.result;
              }
            })
          }
        }else{
          getAction(`/sys/dict/cacheDict/${this.dict}`,{keyword:''}).then(res=>{
            this.loading=false
            if(res.success){
              this.options = res.result
              //console.log("我是第一个",res)
            }else{
              this.$message.warning(res.message)
            }

          })
        }

      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      handleChange (selectedValue) {
        //console.log("selectedValue",selectedValue)
        this.selectedValue = selectedValue
        this.callback()
      },
      handleAsyncChange(selectedObj){
        console.log('selectedObj',selectedObj)
        if(!selectedObj){
          this.selectedValue=null
          this.selectedAsyncValue=null
        }else {
          this.selectedAsyncValue = selectedObj
          this.selectedValue = selectedObj.key
        }

        this.callback()
      },
      callback(){
        this.$emit('change', this.selectedValue);
      },
      setCurrentDictOptions(dictOptions){
        this.options = dictOptions
      },
      getCurrentDictOptions(){
        return this.options
      },
      getNextFocus()
      {
        if (this.clickflag==true) {
          this.$refs.refName.$el.click()
        }
        //this.clickflag==true
      }

    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>

</style>